<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/4
 * Time: 15:50
 */

/**
 * 购物车商品记录字段
 * cartid customer_id member_ident goods_id quantity type(string)
 *
 */


namespace common\components\extenders;

use frontend\models\datas\Goods;
use yii\redis\Connection;


class CartManage extends Connection
{
    // 商品
    public $goods;

    //参数
    public $param;

    //数据库选择
    public $database = 1;

    /**
     * 添加购物车：member_ident customer_id goods_id quantity create_at type
     * 查看购物车：member_ident
     * 修改购物车商品数量：cart:id quantity goods_id
     * 删除购物车中商品：cart:id
     */

    /**
     * 购物车数据放在第 $database 个数据库里
     */
    public function __construct(){
        \Yii::$app->redis->select($this->database);
    }

    /**
     * 添加购物车：
     * 1、验证商品是否可购买、最大购买数量、库存
     * 2、验证购物车中是否有该商品，有：商品数量加1、没有：添加商品
     * 添加购物车：member_ident(设备号) customer_id goods_id quantity create_at type
     * @param $data array
     * @return bool
     */
    public function addCart($data)
    {
        if($this->validateIsBuy($data['goods_id']) && $this->validateMaxBuy($data) && $this->validateNum($data)){
            //时间戳$time $member_ident.$time  用于区分不同用户在相同机器 设备号相同问题
            $time = time();

            //判断用户是否登录，若登陆则查询该用户已存的设备号
            if($data['customer_id'] > 0){
                //若customer：customer_id 存在  则取出
                if(\Yii::$app->redis->executeCommand("EXISTS",["cart:customer:".$data['customer_id']])) {
                        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:" . $data['customer_id']]);
                }else {
                    //若不存在
                    if (\Yii::$app->redis->executeCommand("EXISTS",["cart:member_ident:" . $data['member_ident']  . $data['customer_id']])) {

                        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:member_ident:" . $data['member_ident']  . $data['customer_id']]);

                        //若用户登录，则添加string customer:customer_id => member_ident
                        \Yii::$app->redis->executeCommand("SET",["cart:customer:" . $data['customer_id'],$member_ident]);


                    }else{
                        if(\Yii::$app->redis->executeCommand("EXISTS",["cart:member_ident:0"])) {
                            $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:member_ident:0"]);
                            \Yii::$app->redis->executeCommand("SET",["cart:customer:" . $data['customer_id'],$member_ident]);
                        }else{
                            $member_ident = $data['member_ident'].$time;
                            \Yii::$app->redis->executeCommand("SET",["cart:customer:" . $data['customer_id'],$member_ident]);
                        }
                    }
                }
            }else{

                if(\Yii::$app->redis->executeCommand("EXISTS",["cart:member_ident:" . $data['member_ident'] . $data['customer_id']])) {
                    $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:member_ident:" . $data['member_ident']  . $data['customer_id']]);
                }else{
                    $member_ident = $data['member_ident'].$time;
                    //添加设备号与设备号.time的string
                    \Yii::$app->redis->executeCommand("SET",["cart:member_ident:" . $data['member_ident'] . $data['customer_id'], $member_ident]);
                }
            }
            //判断购物车中是否有该商品
            $inCart = \Yii::$app->redis->executeCommand("SISMEMBER",["cart:good:".$member_ident,$data['goods_id']]);
            if($inCart){
                //若有则修改商品数量
                //找到该商品
                $dataAdd['goods_id'] = $data['goods_id'];

                $dataAdd['cartid'] = \Yii::$app->redis->executeCommand("GET",["cart:".$member_ident.":".$data['goods_id']]);

                $dataAdd['quantity'] = \Yii::$app->redis->executeCommand("HGET",["cart:cart:".$dataAdd['cartid'],'quantity']) + $data['quantity'];

                $isEdit = $this->editCart($dataAdd);

                if($isEdit){
                    return true;
                }else{
                    return false;
                }
            }else{
                //若没有则添加新记录
                //cartid  购物车id自增 若有cartid键 值加一
                $cartId = \Yii::$app->redis->incr('cartid');

                $data['member_ident'] = $member_ident;

                $hdata[] = "cart:cart:".$cartId;
                $hdata[] = 'cart:cartid';
                $hdata[] = $cartId;
                foreach($data as $k=>$v){
                    $hdata[] = $k;
                    $hdata[] = $v;
                }

                //添加购物车商品  添加$cartId 作为主键
                $isAddCart = \Yii::$app->redis->executeCommand('HMSET',$hdata);

                //用来获取该设备号下购物车内商品
                $isSetSign = \Yii::$app->redis->executeCommand("SADD",["cart:cartid:".$data['member_ident'],$cartId]);

                //用来获取该设备号下确认订单内的商品  有的商品在购物车内不加入订单
                $isSetSign = \Yii::$app->redis->executeCommand("SADD",["cart:checkout:".$data['member_ident'],$cartId]);

                //用来判断该购物车是否有该商品
                $isSetGoods = \Yii::$app->redis->executeCommand("SADD",["cart:good:".$data['member_ident'],$data['goods_id']]);

                //用来在商品存在时，查找该购物车的该商品
                $isSerStr = \Yii::$app->redis->executeCommand("SET",["cart:".$data['member_ident'].":".$data['goods_id'],$cartId]);

                if($isAddCart && $isSetSign && $isSerStr && $isSetGoods){
                    return true;
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
    }


    /**
     * 购物车首页
     * 查看购物车,通过设备号查询id  cart:id
     * @param $param array   customer_id  member_ident
     * @return array
     */
    public function getCart($param)
    {
        if($param['customer_id'] >0) {
            $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:" . $param['customer_id']]);
            if(empty($member_ident)){
                $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:member_ident:".$param['member_ident']."0"]);

                //将用户与设备关联号
                \Yii::$app->redis->executeCommand("SET",["cart:customer:" . $param['customer_id'],$member_ident]);
                //删除member_ident:$member_ident.0
                \Yii::$app->redis->executeCommand("DEL",["cart:member_ident:".$param['member_ident']."0"]);
            }
        }else{
            $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:member_ident:".$param['member_ident'].$param['customer_id']]);
        }
        $ids = \Yii::$app->redis->executeCommand("SMEMBERS",["cart:cartid:".$member_ident]);
        $data = [];
        foreach($ids as $v){
            $data[] = \Yii::$app->redis->executeCommand("HGETALL",["cart:cart:".$v]);
        }
        return $data;
    }

    /**
     * 修改购物车商品数量
     * 先验证商品最大购买数量、库存
     * @param $param array cartid quantity goods_id
     * @return bool
     */
    public function editCart($param)
    {
        if($this->validateMaxBuy($param) && $this->validateNum($param)) {
            $isEdit = \Yii::$app->redis->executeCommand("hmset",["cart:cart:" . $param['cartid'], 'quantity', $param['quantity']]);
            if ($isEdit == 1) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 确认订单时，选择购物车内商品 通过 checkout:设备号.$time 实现
     * @param $customer_id int $cartId int
     * @return bool
     *
     */
    public function checkoutCart($customer_id,$cartId)
    {
        //根据$customer_id在 customer:$customer_id 中获取 设备号.$time
        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:".$customer_id]);

        //判断$cartid是否在 checkout:$member_ident
        if(\Yii::$app->redis->executeCommand("SISMEMBER",["cart:checkout:".$member_ident,$cartId])){
            //若在则将该$cartid从checkout:$member_ident移动到cartid:$member_ident中
            $isMove = \Yii::$app->redis->executeCommand("SREM",["cart:checkout:".$member_ident,$cartId]);
        }else{
            //若不在则将该$cartid从cartid:$member_ident移动到checkout:$member_ident中
            $isMove = \Yii::$app->redis->executeCommand("SADD",["cart:cartid:".$member_ident,$cartId]);
        }

        if($isMove){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 清空某会员购物车
     * @param $customer_id int
     * @return bool
     *
     */
    public function flushCart($customer_id){
        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:".$customer_id]);
        if(\Yii::$app->redis->executeCommand("EXISTS",["cart:cartid:".$member_ident]) == 1 && \Yii::$app->redis->executeCommand("EXISTS",["cart:customer:".$customer_id]) == 1) {

            $cartids = \Yii::$app->redis->executeCommand("SMEMBERS", ["cart:cartid:" . $member_ident]);
            foreach ($cartids as $v) {
                $oneGoodsid = \Yii::$app->redis->executeCommand("HGET", ["cart:cart:" . $v, "goods_id"]);

                \Yii::$app->redis->executeCommand("DEL", ["cart:" . $member_ident.":".$oneGoodsid]);
                \Yii::$app->redis->executeCommand("DEL", ["cart:cart:" . $v]);
            }

            \Yii::$app->redis->executeCommand("DEL", ["cart:cartid:" . $member_ident]);
            \Yii::$app->redis->executeCommand("DEL", ["cart:checkout:" . $member_ident]);
            \Yii::$app->redis->executeCommand("DEL", ["cart:good:" . $member_ident]);
            \Yii::$app->redis->executeCommand("DEL", ["cart:customer:" . $customer_id]);

            return true;


        }else{
            return true;
        }


    }


    /**
     * 删除购物车中商品
     * 删除商品相关数据
     * @param $param $cartid int $customer_id int $member_ident string $param
     * @return bool
     */
    public function delCart($param)
    {
        //取得$cartId的内容
        $cart = \Yii::$app->redis->executeCommand("HGETALL",["cart:cart:".$param['cartid']]);
        $keyMem = array_search('cart:member_ident',$cart);
        $member_ident = $cart[$keyMem + 1];
        $keyGoods = array_search('cart:goods_id',$cart);
        $goods_id = $cart[$keyGoods + 1];
        //删除hash中商品记录
        $isDelCart = \Yii::$app->redis->executeCommand("DEL",["cart:cart:".$param['cartid']]);
        //删除good:设备号中goods_id
        $isDelGood = \Yii::$app->redis->executeCommand("SREM",["cart:good:".$member_ident,$goods_id]);
        //删除cartid:设备号中cartid
        $isDelCartId = \Yii::$app->redis->executeCommand("SREM",["cart:cartid:".$member_ident,$param['cartid']]);
        //删除string 设备号:good_id
        $isDelStr = \Yii::$app->redis->executeCommand("DEL",["cart:".$member_ident.":".$goods_id]);

        //判断购物车是否为空
        if(\Yii::$app->redis->executeCommand("EXISTS",["cart:cartid:".$member_ident]) == 0 && \Yii::$app->redis->executeCommand("EXISTS",["cart:customer:".$param['customer_id']]) == 1){
            if($param['customer_id'] > 0) {
                \Yii::$app->redis->executeCommand("DEL",["cart:customer:" . $param['customer_id']]);
            }else{
                \Yii::$app->redis->executeCommand("DEL",["cart:member_ident:" . $param['member_ident']]);
            }
        }

        if($isDelCart && $isDelGood && $isDelCartId && $isDelStr){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 根据cartid获得一条记录
     * @param $cartid int
     * @return array
     *
     */
    public function getOneCart($cartid)
    {
        $good = \Yii::$app->redis->executeCommand("HGETALL",["cart:cart:".$cartid]);
        $cart = [];
        for($i = 0;$i < count($good);$i++){
            $cart[$good[$i]] = $good[$i+1];
            $i++;
        }
        $data[] = $cart;

        return $data;
    }

    public function getOneCartforone($cartid)
    {
        $good = \Yii::$app->redis->executeCommand("HGETALL",["cart:cart:".$cartid]);
        $cart = [];
        for($i = 0;$i < count($good);$i++){
            $cart[$good[$i]] = $good[$i+1];
            $i++;
        }
        return $cart;
    }

    /**
     * 获取订单内商品ID
     * @param $customer_id int
     * @return array
     *
     */
    public function getOrderGoodId($customer_id)
    {
        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:".$customer_id]);
        $cartids = \Yii::$app->redis->executeCommand("SMEMBERS",["cart:checkout:".$member_ident]);

        return $cartids;
    }

    /**
     * 获取订单内商品  没用到？？
     * @param $customer_id int
     * @return array
     */
    public function getOrderGoods($customer_id)
    {
        $member_ident = \Yii::$app->redis->executeCommand("GET",["cart:customer:".$customer_id]);
        $ids = \Yii::$app->redis->executeCommand("SMEMBERS",["cart:checkout:".$member_ident]);
        $data = [];
        foreach($ids as $v){
            $good = \Yii::$app->redis->executeCommand("HGETALL",["cart:cart:".$v]);
            $cart = [];
            for($i = 0;$i < count($good);$i++){
                $cart[$good[$i]] = $good[$i+1];
                $i++;
            }
            $data[] = $cart;
        }
        return $data;
    }

    /**
     * 清空购物车数据
     * @return bool
     */
    public function flushDb()
    {
        return \Yii::$app->redis->executeCommand("FLUSHDB");
    }

    /**
     * 验证是否可以购买
     * @param $goods_id int
     * @return bool
     */
    public function validateIsBuy($goods_id)
    {
        if($this->getClient() == "wechat"){
            return true;
        }else {
            $goods = $this->getGoods($goods_id);
            if ($goods['is_buy'] == 1) {
                return true;
            } else {
                return false;
            }
        }

    }

    /**
     * 验证添加商品数量是否大于最大购买量
     * @param $param array goods_id quantity
     * @return bool
     */
    public function validateMaxBuy($param)
    {
        if($this->getClient() == "wechat"){
            return true;
        }else {
            $goods = $this->getGoods($param['goods_id']);
            if ($goods['nostore_sell'] = 'Y') {
                return true;
            } else {
                if ($goods['max_buy'] < $param['quantity'])
                    return false;
                else
                    return true;
            }
        }
    }

    /**
     * 验证添加商品数量是否大于库存
     * @param $param array goods_id quantity
     * @return bool
     */
    public function validateNum($param)
    {
        if($this->getClient() == "wechat"){
            return true;
        }else {
            $goods = $this->getGoods($param['goods_id']);
            if ($goods['nostore_sell'] = 'Y') {
                return true;
            } else {
                if ($param['quantity'] >= $goods['store'])
                    return true;
                else
                    return false;
            }
        }

    }

    /**
     * 获取goods
     * @param $goods_id int
     * @return array
     */
    public function getGoods($goods_id)
    {
        return Goods::findone($goods_id);
    }

    /**
     * 获取用户登录端
     * $_SERVER['HTTP_HOST'] 获取url 根据url判断
     * 2016-4-5  先判断是不是微信登录
     *
     */
    public function getClient()
    {
        $url = $_SERVER['HTTP_HOST'];
        $perfUrl = explode(".",$url);

        if($perfUrl[0] == "wechat"){
            $client = "wechat";
        }else{
            $client = "fendian";
        }
        return $client;
    }



}